<?php
/**
 * <b>RUBIK IT Solution & Development ltd.</b>
 *
 * PROJECT		: Rubik Ultimate Framework
 * @version 	: 1.1
 * COPYRIGHT    : 2008
 * ------------------------------------------------------
 * 
 * Created on	:  Aug 1, 2008
 * 
 */

// no direct access
define ( '_FW_EXEC', 1 );

require 'runAloneInit.php';
require '../sysProcess/define.php';
require '../sysProcess/initSystem.php';

$folderName = $_REQUEST ['name'];
$moduleObj = $_REQUEST ['module'];

if (empty ( $folderName )) {
	die ();
}

$moduleName = ucfirst ( $folderName ) . "Module";
RRootImporter::cls( 'modules.' . $folderName . '.' . $moduleName );

if (empty ( $moduleObj )) {
	$paramCode = $_REQUEST ['paramCode'];
	if ($paramCode) {
		$params = base64_decode ( $paramCode );
		$params = unserialize ( $params );
	} 
	else {
		// TODO in this case should use session for security
		$params = &$_GET;
	}
	$moduleObj = new $moduleName ( $params, $folderName );
} else {
	$moduleObj = base64_decode ( $moduleObj );
	$moduleObj = unserialize ( $moduleObj );
}
// TODO in this case should use session for security reason
//$moduleObj->setParams($_GET);

$lazyMode = $moduleObj->getParam ( 'lazy' );
if (empty ( $lazyMode )) {
	$lazyMode = $_REQUEST ['lazy'];
}

switch ($lazyMode) {
	case 'ajax' :
		// If the cache param is ennable
		displayModule ( $moduleObj );
		break;
	case 'javascript' :
	default :
		ob_start ();
		displayModule ( $moduleObj );
		$html = ob_get_contents ();
		ob_end_clean ();
		
		header ( 'Content-type: text/javascript; charset: UTF-8' );
		RCoreImporter::cls( 'helper.RStringHelper' );
		$jsString = RStringHelper::escapeString ( $html );
		echo "document.write('{$jsString}');";
		break;
}

function displayModule($moduleObj) {
	$cacheLifeTime = $moduleObj->getParam ( 'cache' );
	if ($cacheLifeTime) {
		$cacheId = $moduleObj->getName()."_".$moduleObj->hash ();
		if (SysCache::startCache ( $cacheId, 'module', $cacheLifeTime)) {
			return;
		}
		$result = displayWithConfig ( $moduleObj );
		SysCache::endCache ('module', $result, $cacheLifeTime);
	} else {
		displayWithConfig ( $moduleObj );
	}
}

function displayWithConfig($moduleObj) {
	$conf = SystemSite::getSiteConfig ();
	if ($conf->debug) {
		$moduleObj->display ();
		return true;
	}
	$result = @$moduleObj->display ();
	if (! $result) {
		return false;
	}
	return true;
}
?>